package com.ywu.app.manage.standard.service;

import com.ywu.admin.user.spi.entity.UserEntity;
import com.ywu.admin.user.spi.spi.UserSpi;
import com.ywu.app.manage.standard.data.YwuAppRepository;
import com.ywu.app.manage.standard.data.YwuAppUserRepository;
import com.ywu.app.manage.standard.dto.YwuAppUserDto;
import com.ywu.app.manage.standard.entity.YwuAppEntity;
import com.ywu.app.manage.standard.entity.YwuAppUserEntity;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.boot.exception.YwuRuntimeException;
import com.ywu.common.entity.PageList;
import com.ywu.common.page.PageService;
import com.ywu.common.result.CommonResult;
import com.ywu.common.utils.TimerIdGenerateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName YwuAppUserService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/7/29 20:13
 * @Version 1.0
 **/
@Service
@Slf4j
public class YwuAppUserService {
    @Autowired
    private YwuAppUserRepository repository;

    @Autowired
    private YwuAppRepository ywuAppRepository;

    @Autowired
    private UserSpi userSpi;

    /**
    * @Author GroundDemo
    * @Description 分页查询
    * @Date 20:22 2024/7/29
    * @Param [ywuAppUserDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> appUserQueryPageList(YwuAppUserDto ywuAppUserDto) {
        // 查询数量
        int count = repository.queryPageCount(ywuAppUserDto);
        // 构建分页参数
        PageService.execPageStartAndEnd(ywuAppUserDto.getPageInfo());
        // 查询分页数据
        List<YwuAppUserEntity> ywuAppUserEntities = repository.queryPageList(ywuAppUserDto);
        if (CollectionUtils.isEmpty(ywuAppUserEntities)) {
            log.warn("appUserQueryPageList ywuAppUserEntities is empty");
            return CommonResult.success(new PageList<>(ywuAppUserDto.getPageInfo().getPageIndex(),
                    ywuAppUserDto.getPageInfo().getPageSize(), 0, new ArrayList<>()));
        }
        // 查询用户信息
        List<Integer> userIds = ywuAppUserEntities.stream().map(YwuAppUserEntity::getUserId).collect(Collectors.toList());
        CommonResult<List<UserEntity>> queryRes = userSpi.queryUserByUserIdBatch(userIds);
        if (Objects.isNull(queryRes) || !"200".equals(queryRes.getCode())) {
            log.error("user.info.query.error");
            throw new YwuRuntimeException("user.info.query.error");
        }
        // 根据查询结果进行拼装
        List<UserEntity> data = queryRes.getData();
        Map<Integer, UserEntity> userMap = data.stream().collect(Collectors.toMap(UserEntity::getId, Function.identity()));
        for (YwuAppUserEntity entity : ywuAppUserEntities) {
            // 根据用户ID进行匹配用户账号
            if (userMap.containsKey(entity.getUserId())) {
                UserEntity userEntity = userMap.get(entity.getUserId());
                entity.setUserAccount(userEntity.getUserAccount());
            }
        }
        // 构建分页对象
        PageList<YwuAppUserEntity> pageList = new PageList<>(ywuAppUserDto.getPageInfo().getPageIndex(),
                ywuAppUserDto.getPageInfo().getPageSize(), count, ywuAppUserEntities);
        return CommonResult.success(pageList);
    }

    /**
    * @Author GroundDemo
    * @Description 创建用户与应用的关联关系
    * @Date 20:27 2024/7/29
    * @Param [ywuAppUserDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> appUserCreateInfo(YwuAppUserDto ywuAppUserDto) {
        // 校验appId是否存在
        YwuAppEntity ywuAppEntity = new YwuAppEntity();
        ywuAppEntity.setAppId(ywuAppUserDto.getAppId());
        YwuAppEntity res = ywuAppRepository.getEntity(ywuAppEntity);
        if (Objects.isNull(res)) {
            return CommonResult.error().setErrorCode("app.id.is.not.exist")
                    .setMessage("应用ID不存在");
        }
        // 查询关联关系是否存在
        YwuAppUserEntity search = new YwuAppUserEntity();
        search.setAppId(ywuAppUserDto.getAppId());
        search.setUserId(ywuAppUserDto.getUserId());
        YwuAppUserEntity entity = repository.getEntity(search);
        if (Objects.nonNull(entity)) {
            // 用户关联关系已存在
            log.debug("appUserCreateInfo app.user.relation.is.exist");
            return CommonResult.error().setErrorCode("app.user.relation.is.exist")
                    .setMessage("用户与应用的关联关系已存在");
        }
        // 构建插入对象
        YwuAppUserEntity ywuAppUserEntity = new YwuAppUserEntity();
        BeanUtils.copyProperties(ywuAppUserDto, ywuAppUserEntity);
        // 设置ID
        ywuAppUserEntity.setId(TimerIdGenerateUtil.nextId());
        ywuAppUserEntity.createInfo(YwuContextHolder.getCurrentContext().getYwuContextUser().getUserAccount());
        repository.addAppUserInfo(ywuAppUserEntity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 删除用户与应用的关联关系
    * @Date 20:34 2024/7/29
    * @Param [ywuAppUserDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> appUserDeleteInfo(YwuAppUserDto ywuAppUserDto) {
        YwuAppUserEntity ywuAppUserEntity = new YwuAppUserEntity();
        BeanUtils.copyProperties(ywuAppUserDto, ywuAppUserEntity);
        repository.deleteAppUserInfoById(ywuAppUserEntity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 删除用户的关联关系
    * @Date 21:55 2024/7/29
    * @Param [appId]
    * @return void
    **/
    public void deleteByAppId(String appId) {
        YwuAppUserDto ywuAppUserDto = new YwuAppUserDto();
        ywuAppUserDto.setAppId(appId);
        repository.deleteByAppId(ywuAppUserDto);
    }

    /**
    * @Author GroundDemo
    * @Description 根据用户ID和appId进行删除授权信息
    * @Date 20:24 2024/8/2
    * @Param [appId, userId]
    * @return void
    **/
    public void deleteByAppIdAndUserId(String appId, Integer userId) {
        YwuAppUserDto ywuAppUserDto = new YwuAppUserDto();
        ywuAppUserDto.setAppId(appId);
        ywuAppUserDto.setUserId(userId);
        repository.deleteByAppIdAndUserId(ywuAppUserDto);
    }

    /**
    * @Author GroundDemo
    * @Description 批量修改原始应用ID为现有修改后的应用ID
    * @Date 20:36 2024/8/2
    * @Param [sourceAppId, destAppId]
    * @return void
    **/
    public void updateAppIdByOriginAppId(String sourceAppId, String destAppId) {
        String updateBy = YwuContextHolder.getCurrentContext().getYwuContextUser().getUserAccount();
        Date updateDate = new Date();
        repository.updateAppIdByOriginAppId(sourceAppId, destAppId, updateBy, updateDate);
    }

    /**
    * @Author GroundDemo
    * @Description 查询应用的用户授权
    * @Date 22:00 2024/8/4
    * @Param [ywuAppUserDto]
    * @return com.ywu.app.manage.standard.entity.YwuAppUserEntity
    **/
    public YwuAppUserEntity getYwuAppUserEntity(YwuAppUserDto ywuAppUserDto) {
        YwuAppUserEntity ywuAppUserEntity = new YwuAppUserEntity();
        BeanUtils.copyProperties(ywuAppUserDto, ywuAppUserEntity);
        return repository.getEntity(ywuAppUserEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 根据用户id删除授权信息
    * @Date 20:00 2025/3/26
    * @Param [ywuAppUserDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> appUserDeleteInfoByUserId(YwuAppUserDto ywuAppUserDto) {
        repository.deleteByUserId(ywuAppUserDto);
        return CommonResult.success(null);
    }
}
